"use client"
import { ConnectButton } from "@rainbow-me/rainbowkit"
import Head from "next/head"
import styles from "../styles/Home.module.css"
import { Button } from "@/components/ui/button"
import { ToastAction } from "@/components/ui/toast"
import { Toaster } from "@/components/ui/toaster"
import { useToast } from "@/components/ui/use-toast"
import { Input } from "@/components/ui/input"
import{ useState } from 'react';
import axios from 'axios'


import {
  useChainId,
  useAccount,
  useContractRead,
  useContractWrite,
  usePrepareContractWrite,
  useWaitForTransaction,
  useSignMessage,
  useBalance,
  useNetwork, useSwitchNetwork,
  
} from 'wagmi';
import abiAvailFaucet from "@/abis/avail-faucet"
import React from 'react';

const CONTRACT_AVAIL_FAUCET = "0xeA1A9A530d630C3999aEaF624ec643AfAfDb71D9"
const contractConfig = {
  address: CONTRACT_AVAIL_FAUCET,
  abi: abiAvailFaucet,
};
const Home = () => {
  const { chain: currentChain } = useNetwork();
  const { chains, pendingChainId, switchNetwork } = useSwitchNetwork();
  const { toast } = useToast()
  const { isConnected, address } = useAccount();
  console.log(address)
  const [mounted, setMounted] = React.useState(false);
  const { data: balance, isError, isLoading } = useBalance({
    address: address,
    watch: true
  })
  // const balance = useBalance({
  //   address: address,
  //   formatUnits: 'ether',
  //   watch: true
  // });
  React.useEffect(() => setMounted(true), []);

  let chainId = useChainId()
  console.log(chainId)

  const [inputValue, setInputValue] = useState('');

  const handleInputChange = (event) => { // 注意这里接收的是直接的input值，不再是事件对象
    console.log(event.target.value)
      setInputValue(event.target.value);
     
  }


  // console.log(contractWriteConfig)

  

  // const { data: minted } = useContractRead({
  //   ...contractConfig,
  //   args: [address],
  //   functionName: 'balanceOf',
  //   watch: true,
  // });

  // console.log(minted)

  // React.useEffect(() => {
    
  //  console.log(totalSupplyData)
  // }, [totalSupplyData]);
  const [isTransfering, setIsTransfering] = React.useState(false);
  const {
    data: signature,
    signMessage,
    reset: resetSignature
  } = useSignMessage({
    onSuccess: (data, variables) => {
      console.log(data)
      console.log(process.env.NEXT_PUBLIC_API_HOST)
      setIsTransfering(true)
      axios({
        method: 'post',
        url: `${process.env.NEXT_PUBLIC_API_HOST}/get_bera`,
        data: {
          signature: data
        }
      }).then(res => {
        console.log(`axios result:`, res.data)
        if(res.data.status) {
          toast({
            title: `Success.`,
            description: `Transferd 0.1 bera to ${res.data.address}`,
            action: (
              <ToastAction altText="Success">Ok</ToastAction>
            ),
          })
        } else {
          toast({
            title: `Failed.`,
            description: `${res.data.msg}`,
            action: (
              <ToastAction altText="Failed">Ok</ToastAction>
            ),
          })
        }
        
      }).finally(() => {
        setIsTransfering(false)
      })
     
    },
  })

  return (
    <div className={styles.container}>
      
      <Head>
        <title>⚡️0x0_zero⚡️'s TookKit</title>
        <meta
          content="Generated by @rainbow-me/create-rainbowkit"
          name="description"
        />
        <link href="/favicon.ico" rel="icon" />
      </Head>

      <main className={styles.main}>
      <Toaster />
      <ConnectButton />
        <h1 className={styles.title}>
          🐻Bera Faucet🐻
        </h1>

        <p className={styles.description}>
        <code className={styles.code}>{ 'Sign a message to get 0.1 Bera instantly. '}</code>
        </p>
        {/* <p className={styles.description}>
        <code className={styles.code}>{ balance?.formatted == 0 && currentChain?.id == 42161 && '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e'}</code>
        </p> */}
        <p>
        </p>
       
        {mounted && isConnected && (
          <Button onClick={() => {
            !isTransfering && signMessage({message: `request to get 0.1 bera.`})
          }}>
            {isTransfering && `Transfering`}
             {!isTransfering && `Send bera to ${address}` }
          </Button>
        )}
       

      {/* <p className={styles.description} >
        <code className={styles.code}>Minted: {minted?.toString()}</code>
        </p> */}
      </main>

      <footer className={styles.footer}>
        <a href="https://twitter.com/0x0_zero" rel="noopener noreferrer" target="_blank">
           ⚡️ <b > 0x0 </b>  ⚡️
        </a>
      </footer>
      
    </div>
     
  )
}

export default Home
